#pragma once

#include <iostream>
#include <cstdlib>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

const char *root = "/";
const char *dev_null = "/dev/null";

void Daemon(bool ischdir, bool isclose)
{
    signal(SIGCHLD, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    if(fork() > 0){
        exit(0);
    }
    setsid();
    if(ischdir){
        chdir(root);
    }
    if(isclose)
    {
        close(0);
        close(1);
        close(2);
    }
    else{
        int fd = open(dev_null, O_RDWR);
        if(fd > 0){
            dup2(fd, 0);
            dup2(fd, 1);
            dup2(fd, 2);
            close(fd);
        }
    }
}